//
//  CustomImagePickUtility.m
//  BSNL_Market
//
//  Created by ayi on 2018/5/11.
//  Copyright © 2018 ayi. All rights reserved.
//


#import "CustomImagePickUtility.h"

//#import <YYCategories/YYCategoriesMacro.h>
#import <AVFoundation/AVFoundation.h>
#import <TZImagePickerController/TZImagePickerController.h>


@interface CustomImagePickUtility()<UIImagePickerControllerDelegate,TZImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, retain) CustomImagePickUtility *strongSlef;
@property (nonatomic, strong) UIImagePickerController *picker;
@property (nonatomic, strong) TZImagePickerController *tzpicker;
@property (nonatomic, assign) BOOL editing;

@end


#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wprotocol"

@implementation CustomImagePickUtility

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.strongSlef = self;
    }
    return self;
}
- (void)dealloc{
    NSLog(@"=========%@", NSStringFromClass(self.class));
    _picker = nil;
    _tzpicker = nil;
    _delegate = nil;
    _strongSlef = nil;
}

+ (CustomImagePickUtility *)showSheet:(__weak UIViewController *)presentVc andTitle:(NSString *)title andImageCount:(NSInteger )count WithEditCamera:(BOOL )editing{
    CustomImagePickUtility *picker = [[CustomImagePickUtility alloc]init];

    picker.delegate = (id <CustomImagePickUtilityDelegate>)presentVc;

    dispatch_async(dispatch_get_main_queue(), ^{
        [picker showSheet:presentVc andTitle:title andImageCount:count WithEditCamera:editing];
    });
    return picker;
}

- (void)showSheet:(UIViewController *)presentVc andTitle:(NSString *)title andImageCount:(NSInteger )count WithEditCamera:(BOOL )editing{
    self.editing = editing;
    [self showSheet:presentVc andTitle:title andImageCount:count];
}

- (void)showSheet:(UIViewController *)presentVc andTitle:(NSString *)title andImageCount:(NSInteger )count{
    @weakify(presentVc);
    @weakify(self);
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self);
        self.strongSlef.delegate = nil;
        self.strongSlef = nil;
    }];

    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        @strongify(presentVc);
        @strongify(self);
        self.tzpicker = [[TZImagePickerController alloc] initWithMaxImagesCount:count columnNumber:4 delegate:self];
        self.tzpicker.isSelectOriginalPhoto = YES;
        // 1.设置目前已经选中的图片数组
        //            imagePickerVc.selectedAssets = self.selectedAssets; // 目前已经选中的图片数组
        // 2. Set the appearance
        // 2. 在这里设置imagePickerVc的外观
        self.tzpicker.navigationBar.barTintColor = [UIColor whiteColor];
        self.tzpicker.oKButtonTitleColorDisabled = [UIColor lightGrayColor];
        self.tzpicker.oKButtonTitleColorNormal = [UIColor greenColor];
        self.tzpicker.naviTitleColor = [UIColor blackColor];
        self.tzpicker.barItemTextColor = [UIColor blackColor];
        self.tzpicker.statusBarStyle = UIStatusBarStyleDefault;
        // 3. Set allow picking video & photo & originalPhoto or not
        // 3. 设置是否可以选择视频/图片/原图
        self.tzpicker.allowPickingImage = YES;
        self.tzpicker.allowPickingOriginalPhoto = YES;
        self.tzpicker.allowPickingVideo = NO;
        
        // 4. 照片排列按修改时间升序
        self.tzpicker.sortAscendingByModificationDate = YES;
        // 你可以通过block或者代理，来得到用户选择的照片.
//        [self.tzpicker setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
//            
//        }];
        [presentVc presentViewController:self.tzpicker animated:YES completion:nil];
    }];
    
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:NSLocalizedString(@"拍照", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        @strongify(presentVc);
        @strongify(self);
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied)
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请在iPhone的“设置->隐私->相机”中允许访问相机" message:nil delegate:nil cancelButtonTitle:NSLocalizedString(@"detail_title4", nil) otherButtonTitles:nil, nil];
            [alert show];
            return;
        }
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        [picker setDelegate:self];
        //设置拍照后的图片可被编辑
        picker.allowsEditing = self.editing;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
       [presentVc presentViewController:picker animated:YES completion:nil];
    }];
    
    
    
    [alert addAction:cancel];
    [alert addAction:action1];
    [alert addAction:action2];
    [presentVc presentViewController:alert animated:YES completion:nil];
}







#pragma mark ----TZImagePickerControllerDelegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(pickPhotoWithImage:)]) {
        [self.delegate pickPhotoWithImage:photos];
    }
    self.strongSlef.delegate = nil;
    self.strongSlef = nil;
}
- (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker{
    self.strongSlef.delegate = nil;
    self.strongSlef = nil;
}


#pragma mark ----UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *original = [info objectForKey:UIImagePickerControllerOriginalImage];
    @weakify(self);
    [picker dismissViewControllerAnimated:YES completion:^{
        @strongify(self);
        if (self.delegate && [self.delegate respondsToSelector:@selector(pickPhotoWithImage:)]) {
            [self.delegate pickPhotoWithImage:@[original]];
        }
        self.strongSlef.delegate = nil;
        self.strongSlef = nil;
    }];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    @weakify(self);
    [picker dismissViewControllerAnimated:YES completion:^{
        @strongify(self);
        self.strongSlef.delegate = nil;
        self.strongSlef = nil;
    }];
}


@end

#pragma clang diagnostic pop
